const http = require('http')
const path = require('path')
const express = require('express')
const app = express()

const pms = process.argv.splice(2)

function getD() {
    for (i in pms) {
        if (fs.existsSync(pms[i]) && fs.statSync(pms[i]).isDirectory()) {
            return pms[i]
        }
    }
    return null
}

function getP() {
    for (i in pms) {
        if (pms[i] > 0) {
            return pms[i]
        }
    }
    return null
}

const D = getD() || path.join(__dirname, 'www')
const P =  getP() || '4444'

console.log('[ pms]', JSON.stringify(arr))
console.log('[ dir]', D)
console.log('[port]', P)

app.use(express.static(D))

app.use(function(req, res, next) {
    console.log(req.method, 404, req.originalUrl)
    res.status(404).send('404 is Fuck')
})

app.use(function(err, req, res, next) {
    console.log(err)
    res.status(500).send('500 Server Error')
})

const server = http.createServer(app)
server.on('error', function(err) {
    console.log(err)
})
server.on('listening', function() {
    console.log('Started, http://127.0.0.1:' + server.address().port + '/')
})
server.listen(P)